package star.cloud.asme.base.redis;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class RedisServiceImpl<T> implements RedisService<T> {

    private final RedisTemplate<String, T> redisTemplate;

    @Value("${spring.application.name}-")
    private String application;

    public void setOne(String key, T value) {
        redisTemplate.opsForValue().set(application + key, value, 3600, TimeUnit.SECONDS);
    }

    public T getOne(String key) {
        return redisTemplate.opsForValue().get(application + key);
    }

    @Override
    public List<T> setList(String key, List<T> value) {
        deleteKey(key);
        ListOperations<String, T> opsForList = redisTemplate.opsForList();
        opsForList.rightPushAll(application + key, value);
        return value;
    }

    @Override
    public List<T> getList(String key) {
        ListOperations<String, T> opsForList = redisTemplate.opsForList();
        return opsForList.range(application + key, 0, opsForList.size(application + key) - 1);
    }

    //删除一个key
    @Override
    public Boolean deleteKey(String key) {
        String key1 = application + key;
        Boolean hasKey = redisTemplate.hasKey(key1);
        if (hasKey) {
            return redisTemplate.delete(key1);
        }
        return false;
    }
}